package com.gct.controller;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.gct.controller.base.BaseController;
import com.gct.service.RepresenterService;

@Controller
@RequestMapping("/upload")
public class UploadingController extends BaseController {
    @Autowired
    private RepresenterService representerService;

    @GetMapping(value = "/video")
    public ModelAndView uploadVideoPage(ModelAndView mv) {
        mv.addObject("reps", representerService.queryReps());
        mv.setViewName("uploadvideo"); // default page
        return mv;
    }

    @GetMapping(value = "/audio")
    public ModelAndView uploadAudioPage(ModelAndView mv) {
        mv.addObject("reps", representerService.queryReps());
        mv.setViewName("uploadaudio");
        return mv;
    }

    @PostMapping(value = "/save", produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody String uploadFile(@RequestParam("name") String name, @RequestParam("profile") String profile, @RequestParam("file") MultipartFile file,
            @RequestParam("fileType") String fileType, RedirectAttributes ratt) {
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                logger.info(bytes.length + "");
                logger.info(name);
                // TODO transcode
            } catch (IOException e) {
                this.processException(e);
            }
        }
        if("v".equals(fileType))
            return "redirect:/upload/video";
        return "redirect:/upload/audio";
    }
}
